import {PlusOutlined} from '@ant-design/icons';
import {Button, Divider, message, Input, Drawer, InputNumber, Select, Form, Modal} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import DepartmentForm from './components/DepartmentForm';
import {queryDepartment, updateDepartment, addDepartment, removeDepartment} from '@/services/system';
import {queryRule} from "@/pages/material/material-manage/service";


const initRecord = {
  departmentName: '',
  departmentCode: '',
  id: '',
  remark: ''
}


const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [formTitle, setFormTitle] = useState('新增部门');
  const [formType, setFormType] = useState(1); // 1:新增 2:更新
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRecord, setSelectedRecord] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const { Option } = Select;
  const handleUpdateModalVisible = (record)=>{
    formRef.setFieldsValue({
      ...record
    })
    setFormType(2)
    setSelectedRecord(record)
    setFormTitle('更新部门')
    handleModalVisible(true)
  }
  const handleCreateModalVisible = ()=>{
    formRef.setFieldsValue({
      ...initRecord
    })
    setFormTitle('新增部门')
    setFormType(1)
    handleModalVisible(true)
  }


  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      await addDepartment({...fields}).then(res=>{
        if (res && res.status === '0') {
          if (actionRef.current) {
            actionRef.current.reload();
          }
          hide();
          message.success('添加成功，即将刷新');
        }else {
          message.error(res.message)
        }
      })
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const handleUpdate = async (fields) => {
    fields.id = selectedRecord.id
    const hide = message.loading('正在配置');

    try {
      await updateDepartment({...fields}).then(res=>{
        if (res && res.status === '0') {
          if (actionRef.current) {
            actionRef.current.reload();
          }
          hide();
          message.success('配置成功，即将刷新');
        }else {
          message.error(res.message)
        }
      })
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeDepartment({
        idList: [
          selectedRows.id
        ]
      }).then(res=>{
        hide();
        if (res && res.status === '0') {
          if (actionRef.current) {
            actionRef.current.reload();
          }
          message.success('删除成功，即将刷新');
        }else {
          message.error(res.message)
        }
      });

      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined />,
      content: `是否要删除 【${record.departmentName} 】？`,
      okText: '确认',
      cancelText: '取消',
      onOk: ()=>{
        handleRemove(record)
      }
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '部门名称',
      dataIndex: 'departmentName',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
    },
    {
      title: '部门编码',
      dataIndex: 'departmentCode',
      hideInSearch: true
    },
    {
      title: '创建人',
      dataIndex: 'createByName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical"/>,
        <a onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        <Divider type="vertical"/>,
        <a onClick={()=> deleteConfig(record) }>删除</a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新增部门
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {...params, size: params.pageSize };
          const res = await queryDepartment(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
      />
      <DepartmentForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {
            const success = formType === 1? await handleAdd(value): await handleUpdate(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="key"
          type="form"
          columns={columns}
        />
      </DepartmentForm>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.departmentName && (
          <ProDescriptions
            column={2}
            title={row?.departmentName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.departmentName,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
